package com.zheng.oa.admin.controller.hr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.CamelUnderlineConverter;
import com.zheng.common.validator.DecimalValidator;
import com.zheng.common.validator.LengthValidator;
import com.zheng.hr.dao.model.HrRecruitPlan;
import com.zheng.hr.dao.model.HrRecruitRequire;
import com.zheng.hr.rpc.api.HrRecruitPlanService;
import com.zheng.hr.rpc.api.HrRecruitRequireService;
import com.zheng.oa.common.constant.OaResult;
import com.zheng.oa.common.constant.OaResultConstant;
import com.zheng.oa.common.exception.OaException;
import com.zheng.upms.rpc.api.UpmsApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2018/1/18
 * Time: 11:16
 */
@Controller
@Api(value = "招聘计划管理", description = "招聘计划管理")
@RequestMapping("/oa/hr/recruitPlan")
public class HrRecruitPlanController extends BaseController {
    @Autowired
    private HrRecruitPlanService recruitPlanService;
    @Autowired
    private HrRecruitRequireService recruitRequireService;
    @Autowired
    private UpmsApiService apiService;
    @ApiOperation(value = "岗招聘计划首页")
    @RequiresPermissions("oa:hr:recruitPlan:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/manage/hr/recruitPlan/index.jsp";
    }

    @ApiOperation(value = "岗招聘计划列表")
    @RequiresPermissions("oa:hr:recruitPlan:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                       @RequestParam(required = false, defaultValue = "", value = "searchText") String searchText,
                       @RequestParam(required = false, value = "sortName") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder) {
        Wrapper<HrRecruitPlan> wrapper = new EntityWrapper<>();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            if (sortOrder.equalsIgnoreCase("asc")) {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), true);
            } else {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), false);
            }
        }
        if (StringUtils.isNotBlank(searchText)) {
            wrapper.like("name", searchText);
        }
        wrapper = apiService.dataScopeFilter(wrapper, getUsername());
        Page<HrRecruitPlan> page = recruitPlanService.selectPage(new Page<>(pageNumber, pageSize), wrapper);
        int total = recruitPlanService.selectCount(wrapper);

        Map<String, Object> result = new HashMap<>();
        result.put("rows", page.getRecords());
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增招聘计划")
    @RequiresPermissions("oa:hr:recruitPlan:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        return "/manage/hr/recruitPlan/create.jsp";
    }

    @ApiOperation(value = "新增招聘计划")
    @RequiresPermissions("oa:hr:recruitPlan:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody JSONObject param) {
        HrRecruitPlan recruitPlan = param.toJavaObject(HrRecruitPlan.class);
        List<HrRecruitRequire> requires = param.getJSONArray("requires").toJavaList(HrRecruitRequire.class);
        if (requires.size() < 1) {
            return new OaResult(OaResultConstant.FAILED, "未设置招聘需求！");
        }
        ComplexResult result = FluentValidator.checkAll()
                .on(recruitPlan.getName(), new LengthValidator(0, 20, "招聘计划名称"))
                .on(recruitPlan.getMoney(), new DecimalValidator(0, 8, "预算费用"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new OaResult(OaResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        try {
            recruitPlanService.insetRecruitPlan(recruitPlan, requires);
        } catch (OaException e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }
    @ApiOperation(value = "编辑招聘计划")
    @RequiresPermissions("oa:hr:recruitPlan:update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(Model model,Integer id) {
        HrRecruitPlan recruitPlan = recruitPlanService.selectById(id);
        EntityWrapper<HrRecruitRequire> recruitRequireEntityWrapper = new EntityWrapper<>();
        recruitRequireEntityWrapper.where("plan_id=" + id);
        List<HrRecruitRequire> hrRecruitRequires = recruitRequireService.selectList(recruitRequireEntityWrapper);
        model.addAttribute("recruitPlan", recruitPlan);
        model.addAttribute("hrRecruitRequires", JSON.toJSON(hrRecruitRequires));

        return "/manage/hr/recruitPlan/update.jsp";
    }
    @ApiOperation(value = "编辑招聘计划")
    @RequiresPermissions("oa:hr:recruitPlan:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody JSONObject param) {
        HrRecruitPlan recruitPlan = param.toJavaObject(HrRecruitPlan.class);
        List<HrRecruitRequire> requires = param.getJSONArray("requires").toJavaList(HrRecruitRequire.class);
        if (requires.size() < 1) {
            return new OaResult(OaResultConstant.FAILED, "未设置招聘需求！");
        }
        ComplexResult result = FluentValidator.checkAll()
                .on(recruitPlan.getName(), new LengthValidator(0, 20, "招聘计划名称"))
                .on(recruitPlan.getMoney(), new DecimalValidator(0, 8, "预算费用"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new OaResult(OaResultConstant.FAILED, result.getErrors().get(0).getErrorMsg());
        }
        try {
            recruitPlanService.updateRecruitPlan(recruitPlan, requires);
        } catch (OaException e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }
    @ApiOperation(value = "删除招聘计划")
    @RequiresPermissions("oa:hr:recruitPlan:delete")
    @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        try {
            if (recruitPlanService.deleteRecruitPlan(ids)) {
                return new OaResult(OaResultConstant.SUCCESS, null);
            } else {
                return new OaResult(OaResultConstant.FAILED, null);
            }
        } catch (OaException e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());

        }
    }
}
